<style>
.image {
  width: 100%;
  display: block;
}
</style>
<template>
	<div id="suggest_approve">
		<!--工具条-->
		<div name="searchColums">
			<el-form :inline="true"
			         :model="filters"
			         size="small"
			         ref="filters"
			         class="searchForm">
				<el-form-item class="el-form-item"
				              label="报修人" prop="liftUserName">
				<el-input  class="filter-item" placeholder="报修人姓名" v-model="filters.liftUserName"></el-input>
				</el-form-item>
				<el-form-item class="el-form-item"
				              label="报修时间" prop="startTimeBegin">
					<el-date-picker v-model="filters.startTimeBegin"
					                type="date"
					                value-format="yyyy-MM-dd"
					                placeholder="选择日期"></el-date-picker>
				</el-form-item>
				<el-form-item class="el-form-item"
				              label="至" prop="startTimeEnd">
					<el-date-picker v-model="filters.startTimeEnd"
					                type="date"
					                value-format="yyyy-MM-dd"
					                placeholder="选择日期"></el-date-picker>
				</el-form-item>
        <el-form-item  label="状态">
          <el-select size="small" v-model="filters.status" clearable placeholder="请选择">
            <el-option v-for="item in statusOptions" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
				<span class="bth_search">
					<el-form-item>
						<el-button type="success"
						           icon="el-icon-search"
						           v-on:click="getDataGrid(true)">查询</el-button>
					</el-form-item>
					<el-form-item>
						<el-button icon="el-icon-refresh"
						           @click="resetSearchForm('filters')">重置</el-button>
					</el-form-item>
				</span>
			</el-form>
		</div>
		<!--toolbar-->
		<el-row id="toolbar_unit">
			<el-col :span="24">
				<div class="grid-content bg-purple-light">
					<el-button type="success"
					           size="mini"
					           icon="el-icon-check"
					           :disabled="this.sels.length===0"
					           @click="handleAccept">受理</el-button>
					<el-button type="primary"
					           size="mini"
					           @click="handleFenpei"
					           :disabled="this.sels.length===0"
					           icon="el-icon-upload">分配</el-button>
				</div>
			</el-col>
		</el-row>

		<!--列表-->
		<el-table :data="gridDatas"
		          id="dataGrid"
		          empty-text=" "
		          border
		          stripe
		          size="mini"
		          :header-row-class-name="headStyle"
		          highlight-current-row
		          v-loading="listLoading"
		          :row-class-name="tableRowClassName"
		          @sort-change="handleSortChange"
		          @selection-change="selsChange"
		          style="width: 100%;">
			<el-table-column type="selection"
			                 width="45"></el-table-column>
			<el-table-column prop="index"
			                 :formatter="index_formatter"
			                 label="序号"
			                 width="60"></el-table-column>
			<el-table-column prop="liftUserName"
			                 label="报修人姓名"
			                 width="120"
			                 show-overflow-tooltip></el-table-column>
			<el-table-column prop="startTime"
			                 label="报修时间"
			                 width="140"
			                 show-overflow-tooltip></el-table-column>
			<el-table-column prop="description"
			                 label="问题描述"
			                 show-overflow-tooltip></el-table-column>
			<el-table-column label="图片"
			                 width="100">
				<template slot-scope="scope">
					<el-button round
					           @click="showImgPath('repair', scope.row)">查看</el-button>
				</template>
			</el-table-column>
			<el-table-column prop="repairUserName"
			                 label="维修人员"
			                 width="80"
			                 show-overflow-tooltip></el-table-column>
			<el-table-column prop="repairResultName"
			                 label="维修结果"
			                 width="80"
			                 show-overflow-tooltip></el-table-column>
			<el-table-column prop="resultImg"
			                 label="维修结果图片"
			                 width="140"
			                 show-overflow-tooltip>
			  <template slot-scope="scope">
					<el-button round
					           @click="showImgPath('repair_result', scope.row)">查看</el-button>
				</template>
			</el-table-column>
			<el-table-column prop="operationDescription"
			                 label="维修描述"
			                 show-overflow-tooltip></el-table-column>
			<el-table-column prop="statusName"
			                 label="报修状态"
			                 width="80"
			                 show-overflow-tooltip></el-table-column>
		</el-table>

		<!--工具条-->
		<el-col :span="24"
		        class="toolbar"
		        id="pageDiv">
			<el-pagination small
			               background
			               @current-change="handleCurrentChange"
			               @size-change="handleSizeChange"
			               :page-sizes="[10, 20, 50, 100]"
			               :page-size="pageSize"
			               :total="total"
			               layout="total,sizes, prev, pager, next"
			               style="float:right;"></el-pagination>
		</el-col>

		<!--图片查看界面-->
		<el-dialog title="报修图片"
		           :visible.sync="imgFormVisible"
		           :close-on-click-modal="false">
			<el-row>
				<el-col v-for="(imgPath,index) in imgListShow"
				        :key="index">
					<el-card :body-style="{ padding: '0px' }">
						<img :src="imgPath.data"
						     class="image" />
					</el-card>

				</el-col>
			</el-row>
		</el-dialog>

		<!--维修人选择界面-->
		<el-dialog title="选择"
		           :visible.sync="userSelectFormVisible"
		           :close-on-click-modal="false">
			<el-tree :props="defaultProps" :load="loadChildrenNode" lazy
               highlight-current node-key="id" :expand-on-click-node="false" ref="tree" accordion
               @node-click="getNodeData">
      </el-tree>
		</el-dialog>

	</div>
</template>
<script>
import { getToken, setToken, removeToken,getFileIp } from "@/util/auth";
import { getUUID } from "@/util/util";
import request from "@/router/axios";
export default {
  name: "repairApprove",
  data() {
    return {
      statusOptions: [],
      communityOptions: [],
      buildingOptions: [],
      unitOptions: [],
      houseOptions: [],
      liftUserOptions: [{
          id: '',
          name: ''
        }],
      //单元过滤条件
      filters: {
        liftUserName: "",
        startTimeBegin: "",
        startTimeEnd: "",
        status: ''
      },
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      url: {
        //单元数据
        list: "/admin/repairRecord/page",
        save: "/admin/repairRecord/add",
        approve: "/admin/repairRecord/approve",
        submitSug: "/admin/repairRecord/fenpei"
      },
      gridDatas: [],
      suggestTypeOptions: [],
      sort: {
        sort: "sort",
        order: "asc"
      },
      total: 0,
      page: 1,
      pageSize: 10,
      listLoading: false,
      sels: [],
      imgPaths: [],
      uploadParams: { type: "repair",relationId:"" },
      imgList: [],
      imgListShow: [],
      editLoading: false,
      editFormVisible: false,
      addFormVisible: false,
      editForm: {},
      addForm: {
      	id:undefined,
      	buildingId:undefined,
      	unitId:undefined,
      	houseId:undefined,
      	liftUser:undefined,
      	description:undefined
      },
      editFormRules: {},
      addFormRules: {
        liftUser: [
          {
            required: true,
            message: '请选择业主 '
          }
        ],
        description: [
          {
            required: true,
            message: '请填写问题描述 '
          }
        ],
      },
      userSelectFormVisible: false,
      imgFormVisible: false,
      userSelectLoading: false,
      userSelectForm: {},
      uploadHeader: {
        Authorization: "Bearer " + getToken()
      }
    };
  },
  methods: {

    //初始化下拉框
    initData: function() {
      request.get("/admin/community?getCommunitysByUserId").then((res) => {
        if (res.status === 200) {
          this.communityOptions = res.data
        }
      })
      request.get("/admin/dict/type/repair_status").then((res) => {
        if (res.status === 200) {
          this.statusOptions = res.data
        }
      })
    },
    handleAddBeforeClose(){
    	this.$refs.addForm.resetFields();
    },
    handleSelectBuilding() {
      this.addForm.buildingId = '';
      this.addForm.unitId = '';
      this.addForm.houseId = '';
      this.addForm.liftUser = '';
      request.get("/admin/communityBuilding/getCommunityBuildings/" + this.addForm.communityId).then((res) => {
        if (res.status === 200) {
          this.buildingOptions = res.data
        }
      });
    },
    handleSelectUnit() {
      this.addForm.unitId = '';
      this.addForm.houseId = '';
      this.addForm.liftUser = '';
      request.get("/admin/communityBuilding/getBuildingUnits/" + this.addForm.buildingId).then((res) => {
        if (res.status === 200) {
          // 判断楼宇下单元数据是否为空
          if (res.data.length === 0) {
            // 说明该楼宇下没有单元数据，直接去获取到房屋列表
            this.unitOptions = [];
            request.get("/admin/unitHouse/getUnitHousesByBuildingId/" + this.addForm.buildingId).then((res) => {
              if (res.status === 200) {
                this.houseOptions = res.data
              }
            });
          } else {
            this.unitOptions = res.data;
          }
        }
      });
    },
    handleSelectHouse() {
      this.addForm.houseId = '';
      this.addForm.liftUser = '';
      request.get("/admin/unitHouse/getUnitHouses/" + this.addForm.unitId).then((res) => {
        if (res.status === 200) {
          this.houseOptions = res.data;
        }
      });
    },
    handleSelectUser() {
      this.addForm.liftUser = '';
      request.get("/admin/houseOwner/getHouseOwners/" + this.addForm.houseId).then((res) => {
        if (res.status === 200) {
          this.liftUserOptions = res.data;
        }
      });
    },
    handleSortChange(sort) {
      this.sort = {
        sort: sort.prop,
        order: sort.order == "ascending" ? "asc" : "desc"
      };
      this.getDataGrid();
    },
    tableRowClassName(row, index) {
      //把每一行的索引放进row
      row.index = row.rowIndex;
    },
    headStyle({ row, rowIndex }) {
      return "table_head_style";
    },
    index_formatter: function(row, column, cellValue, index) {
      //放回索引值
      return this.pageSize * (this.page - 1) + 1 + index;
    },
    handleCurrentChange(val) {
      this.page = val;
      this.getDataGrid();
    },
    handleSizeChange(val) {
      this.pageSize = val;
      this.page = 1;
      this.getDataGrid();
    },
    resetSearchForm(formName) {
      this.$refs.filters.resetFields();
    },
    selsChange: function(sels) {
      this.sels = sels;
    },
    handleFenpei: function() {
    	for(var i=0;i<this.sels.length;i++){
    		if(this.sels[i].status=='0'){
    			this.$message({
	            message: '记录未受理，请先受理。',
	            type: 'info',
	            duration: 1500
	          });
	          return;
    		}
    		if(this.sels[i].status!='1'){
    			this.$message({
	            message: '记录已派单。',
	            type: 'info',
	            duration: 1500
	          });
	          return;
    		}
    	}
      this.userSelectFormVisible = true;
    },
    //图片点击事件
    imgHandlePreview: function(file) {},
    //图片删除事件
    imgHandleRemove: function(file, fileList) {},
    //图片上传之前验证格式
    beforeImgUpload: function(file) {
      const type = file.type;
      const flag =
        type == "image/jpeg" ||
        type == "image/gif" ||
        type == "image/png" ||
        type == "image/bmp";
      if (!flag) {
        this.$message.error("只支持上传图片!");
      }

      return flag;
    },

    //图片上传成功后
    imgSuccess: function(response, file, fileList) {
//    var path = response.attributes.filepath;
//    this.imgPaths.push(path);
    },
    showImgPath: function(type, row) {
      this.imgListShow = [];
      let para = { id: row.id,type:type };
        request({
          url: "/admin/repairRecord/showImg",
          method: "get",
          params: para
        }).then(res => {
        	for (var i = 0; i < res.data.length; i++) {
	          var img = {}
	          img.id = res.data[i].id
	          img.data = getFileIp() + res.data[i].data
	          this.imgListShow.push(img)
        }

        });
      this.imgFormVisible = true;
    },
    loadChildrenNode(node, resolve) {
      if (node.level === 0) {
        request.get("/admin/community?getCommunitysByCurrentUser").then((res) => {
          if (res.status === 200) {
            return resolve(res.data);

          }
        });

      } else if (node.level === 1) {
        //点击小区节点，获取角色列表
        request.get("/admin/repairRecord/roleList/"+node.data.id).then((res) => {
          if (res.status === 200) {
            return resolve(res.data);
          }
        });
      } else if (node.level === 2) {
        //点击角色节点，获取角色下面所有用户
        request.get("/admin/user/userList/" + node.data.id+"/"+node.parent.data.id).then((res) => {
          if (res.status === 200) {
            return resolve(res.data);
          }
        });
      } else {
        return resolve([]);
      }

    },
    getNodeData(e,node,data) {
    	if(node.level==3){
    		// 获取到要分配的维修员的id
        var acceptUserId = e.userId;
        var name = e.name;
        var ids = this.sels.map(item => item.id).toString();
        this.$confirm("确认将选中的报修单指派给"+name+"吗?", '提示', {
        type: 'warning'
      	}).then(() => {
      		this.userSelectFormVisible=false;
	        this.listLoading = true;
	        let para = {
	          userId: acceptUserId,
	          repairStatus:"2",
	          ids:ids
	        };
	        request.get("/admin/repairRecord/updateRepairStatus", {
	          params: para
	        }).then((res) => {
	          this.listLoading = false;
	          this.$message({
	            message: '指派成功',
	            type: 'success',
	            duration: 1500
	          });
	          this.getDataGrid();
	        });
      	}).catch(() => {
      	});
    	}

    },

    //受理
    handleAccept: function() {
    	for(var i=0;i<this.sels.length;i++){
    		if(this.sels[i].status!='0'){
    			this.$message({
	            message: '记录已受理',
	            type: 'info',
	            duration: 1500
	          });
	          return;
    		}
    	}
    	var ids = this.sels.map(item => item.id).toString();
        this.$confirm("确认受理吗?", '提示', {
        type: 'warning'
      	}).then(() => {
	        this.listLoading = true;
	        let para = {
	          userId: "",
	          repairStatus:"1",
	          ids:ids
	        };
	        request.get("/admin/repairRecord/updateRepairStatus", {
	          params: para
	        }).then((res) => {
	          this.listLoading = false;
	          this.$message({
	            message: '受理成功',
	            type: 'success',
	            duration: 1500
	          });
	          this.getDataGrid();
	        });
      	}).catch(() => {
      	});
    },
    //编辑
    editSubmit: function() {
      this.$refs.editUnitForm.validate(valid => {
        if (valid) {
          this.$confirm("确认提交吗？", "提示", {}).then(() => {
            this.editUnitLoading = true;
            let para = Object.assign({}, this.editUnitForm);
            request.post(this.url.unitEdit, para).then(res => {
              this.editUnitLoading = false;
              this.$message({
                message: "提交成功",
                type: "success",
                duration: 1500
              });
              this.$refs["editUnitForm"].resetFields();
              this.editUnitFormVisible = false;
              this.getDataGrid();
            });
          });
        }
      });
    },
    addSubmit: function() {
      this.$refs.addForm.validate(valid => {
        if (valid) {
          this.$confirm("确认提交吗？", "提示", {}).then(() => {
            this.editLoading = true;
            this.addForm.imgPath = this.imgPaths.toString();
            let param = Object.assign({}, this.addForm);
            request.post(this.url.save, param).then(res => {
              this.editLoading = false;
              this.$message({
                message: "提交成功",
                type: "success",
                duration: 1500
              });
              this.$refs["addForm"].resetFields();
              this.addFormVisible = false;
              this.getDataGrid();
            });
          });
        }
      });
    },

    //获取单元列表数据
    getDataGrid(flag) {
      //获取当前树节点选中小区
      if(flag){
      	this.page = 1;
      }
      let para = {
        params: {
          page: this.page,
          limit: this.pageSize,
          //排序
          orderByField: this.sort.sort,
          isAsc: this.sort.order,
          type:"1",
          liftUserName: this.filters.liftUserName,
          startTimeBegin: this.filters.startTimeBegin,
          startTimeEnd: this.filters.startTimeEnd,
          status: this.filters.status
        }
      };
      this.listLoading = true;
      request.get(this.url.list, para).then(res => {
        this.total = res.data.total;
        var datas = res.data.records;
        this.gridDatas = datas;
        this.listLoading = false;
      });
    }
  },
  mounted() {
    this.getDataGrid();
    this.initData();
  }
};
</script>
